<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的帖子</span>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="已发布" name="published"></el-tab-pane>
        <el-tab-pane label="草稿" name="draft"></el-tab-pane>
      </el-tabs>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="posts.length === 0" class="empty-tip">
        <el-empty description="暂无帖子"></el-empty>
      </div>

      <div v-else>
        <div v-for="post in posts" :key="post.id" class="post-item">
          <div class="post-header">
            <h3 class="post-title" @click="handleComment(post.id)">{{ post.title }}</h3>
            <el-tag size="small" :type="getStatusType(post.status)">{{ getStatusText(post.status) }}</el-tag>
          </div>
          
          <p class="post-content">{{ post.content }}</p>
          
          <div class="post-footer">
            <div class="post-actions">
              <el-button
                type="text"
                :icon="post.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"
                @click="handleLike(post.id)"
              >
                {{ post.likeCount || '点赞' }}
              </el-button>
              <el-button
                type="text"
                :icon="post.isFavorited ? 'el-icon-collection' : 'el-icon-collection-tag'"
                @click="handleFavorite(post.id)"
              >
                {{ post.favoriteCount || '收藏' }}
              </el-button>
              <el-button
                type="text"
                icon="el-icon-chat-line-round"
                @click="handleComment(post.id)"
              >
                {{ post.commentCount || '评论' }}
              </el-button>
            </div>
            <div class="post-meta">
              <span class="post-time">{{ formatTime(post.createTime) }}</span>
            </div>
          </div>
        </div>

        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'MyPosts',
  data() {
    return {
      activeTab: 'all',
      loading: false,
      posts: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      userId: ''
    }
  },
  created() {
    // 打印store信息
    console.log('完整store信息:', this.$store);
    console.log('store.state.user:', this.$store.state.user);
    
    // 从store获取用户ID
    let userId = this.$store.state.user.id || '';
    console.log('store中的userId:', userId);
    
    if (!userId) {
      // 尝试其他方法获取userId
      userId = localStorage.getItem('userId') || sessionStorage.getItem('userId') || '';
      console.log('从storage获取userId:', userId);
      
      if (!userId) {
        this.$message.warning('无法获取用户ID，将尝试使用默认ID (3)');
        userId = '3'; // 默认使用ID为3的用户
      }
    }
    
    // 确保userId是数字类型
    this.userId = parseInt(userId, 10);
    console.log('最终使用的userId(数字类型):', this.userId);
    
    this.fetchMyPosts()
  },
  methods: {
    fetchMyPosts() {
      this.loading = true
      
      const status = this.activeTab === 'all' ? null : this.getStatusValue(this.activeTab)
      
      // 提前显示userId是否正确
      console.log('请求参数:', {
        page: this.currentPage - 1,
        size: this.pageSize,
        status: status,
        userId: this.userId
      });
      
      request({
        url: '/api/community/my-posts',
        method: 'get',
        params: {
          page: this.currentPage - 1,
          size: this.pageSize,
          status: status,
          userId: this.userId
        }
      }).then(response => {
        console.log('获取我的帖子响应:', response)
        if (response && response.posts) {
          this.posts = response.posts.map(post => ({
            ...post,
            likeCount: post.likeCount || 0,
            favoriteCount: post.favoriteCount || 0,
            commentCount: post.commentCount || 0,
            isLiked: !!post.isLiked,
            isFavorited: !!post.isFavorited
          }))
          this.total = response.totalItems || 0
          this.currentPage = (response.currentPage || 0) + 1
        }
      }).catch(error => {
        console.error('获取我的帖子失败:', error)
        this.$message.error('获取帖子列表失败，请稍后再试')
      }).finally(() => {
        this.loading = false
      })
    },
    handleTabChange() {
      this.currentPage = 1
      this.fetchMyPosts()
    },
    handlePageChange(page) {
      this.currentPage = page
      this.fetchMyPosts()
    },
    handleLike(postId) {
      request({
        url: `/api/community/posts/${postId}/like`,
        method: 'post',
        params: {
          userId: this.userId  // 添加userId参数
        }
        // 不指定headers，让request.js自动处理认证头
      }).then(response => {
        const post = this.posts.find(p => p.id === postId)
        if (post) {
          post.likeCount = response.likeCount
          post.isLiked = response.isLiked
          this.$message.success(response.isLiked ? '点赞成功' : '已取消点赞')
        }
      }).catch(error => {
        console.error('点赞失败:', error)
        this.$message.error('点赞失败，请稍后再试')
      })
    },
    handleFavorite(postId) {
      request({
        url: `/api/favorites/toggle/${postId}`,
        method: 'post',
        params: {
          userId: this.userId  // 仍然保留userId参数，因为后端可能会使用它作为备用认证
        }
        // 不指定headers，让request.js自动处理认证头
      }).then(response => {
        const post = this.posts.find(p => p.id === postId)
        if (post) {
          post.favoriteCount = response.favoriteCount
          post.isFavorited = response.isFavorited
          this.$message.success(response.isFavorited ? '收藏成功' : '已取消收藏')
        }
      }).catch(error => {
        console.error('收藏失败:', error)
        this.$message.error('收藏失败，请稍后再试')
      })
    },
    handleComment(postId) {
      this.$router.push(`/community/post/${postId}`)
    },
    formatTime(time) {
      return parseTime(time)
    },
    getStatusType(status) {
      switch(parseInt(status)) {
        case 0: return 'success'  // 已发布
        case 3: return 'info'     // 草稿
        default: return ''
      }
    },
    getStatusText(status) {
      switch(parseInt(status)) {
        case 0: return '已发布'
        case 3: return '草稿'
        default: return '未知状态'
      }
    },
    getStatusValue(tab) {
      switch(tab) {
        case 'published': return 0  // 已发布状态
        case 'draft': return 3      // 草稿状态
        default: return null        // 全部状态
      }
    }
  }
}
</script>

<style scoped>
.loading-container {
  padding: 20px;
}

.empty-tip {
  padding: 50px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.post-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.post-item:last-child {
  border-bottom: none;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.post-title {
  margin: 0;
  font-size: 16px;
  color: #303133;
  cursor: pointer;
}

.post-title:hover {
  color: #409EFF;
}

.post-content {
  margin: 10px 0;
  color: #606266;
  line-height: 1.6;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-actions {
  display: flex;
  gap: 15px;
}

.post-meta {
  color: #909399;
  font-size: 13px;
}

.post-time {
  margin-left: 10px;
}
</style>
